<template>
  <div>
    <Form ref="form" :model="formItem" :label-width="100">
      <FormItem label="过期时间" prop="expireTime">
        <Badge v-if="formItem.isExpired" text="授权已过期">
          <DatePicker
            v-model="formItem.expireTime"
            class="ivu-form-item-error"
            type="datetime"
            placeholder="设置有效期"></DatePicker>
        </Badge>
        <DatePicker v-else="" v-model="formItem.expireTime" type="datetime" placeholder="设置有效期"></DatePicker>
      </FormItem>
      <FormItem label="App" prop="granApps">
        <Select filterable 
          not-found-text="无" 
          v-model="formItem.grantApp"
          @on-change="selectChange">
          <Option
            v-for="item in selectApps"
            :value="item.appId"
            :key="item.appId"
          >{{ item.appName }}</Option>
        </Select>
      </FormItem>
      <FormItem label="功能权限" prop="grantMenus">
        <vxe-table
          border
          resizable
          ref="tree"
          row-id="menuId"
          :tree-config="{children: 'children',expandAll: true}"
          :select-config="{labelField: 'menuName',checkRowKeys: checkRowKeys,checkStrictly:true,showHeader:true}"
          :data.sync="selectMenus"
          @select-change="menuAuthorityChange">
          <vxe-table-column type="checkbox" field="menuId" title="菜单" tree-node width="220"></vxe-table-column>
          <vxe-table-column field="operation" title="操作">
            <template v-slot="{ row }">
              <CheckboxGroup v-model="formItem.grantActions">
                <Checkbox v-for="item in row.actionList" :label="item.authorityId">
                  <span :title="item.actionDesc">{{ item.actionName }}</span>
                </Checkbox>
              </CheckboxGroup>
            </template>
          </vxe-table-column>
        </vxe-table>
      </FormItem>
    </Form>
  </div>
</template>

<script>
import XEUtils from 'xe-utils'

export default {
  name: 'RoleAuth',
  data () {
    return {
      selectMenus: [],
      pageInfo: {},
      checkRowKeys: [],
      selectApps: [],
      formItem: this.getFormItem(),
      // 预加载数据
      loadSuccess: false,
      asyncData1: {},
      asyncData2: {},
      changed: false
    }
  },
  methods: {
    getFormItem () {
      return {
        roleId: '',
        grantMenus: [],
        grantActions: [],
        expireTime: '',
        isExpired: false,
        grantApp: '',
        preGrantApp: ''
      }
    },
    /* 初始数据 */
    setData (data) {
      if (data && data.roleId) {
        this.formItem = Object.assign({}, this.formItem, data)
        this.handleLoadRoleApps(data.roleId)
      }
    },
    handleReset () {
      this.$refs['form'].resetFields()
      this.formItem = this.getFormItem()
    },
    menuAuthorityChange ({row, rowIndex, checked}) {
      this.changed = true
      this.childrenChangeSelection(row.children, checked)
    },
    childrenChangeSelection (children, checked) {
      if (children) {
        children.map(item => {
          this.childrenChangeSelection(item.children, checked)
        })
        this.$refs['tree'].setSelection(children, checked);
      }
    },
    /* 提交授权 */
    handleSubmit () {
      this.dealWithSubmit(this.formItem.grantApp)
    },
    dealWithSubmit (grantApp) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const authorityIds = this.getCheckedAuthorities()
          this.$http.post(this.$apis.authority.roleGrantA, {
            roleId: this.formItem.roleId,
            expireTime: this.formItem.expireTime ? this.formItem.expireTime.pattern('yyyy-MM-dd HH:mm:ss') : '',
            authorityIds: authorityIds.join(','),
            appId: grantApp
          }, this).then(res => {
            this.$Message.success({content: '保存成功'})
            this.changed = false
            // this.$bus.emit('closeModal')
          })
        }
      })
    },
    /* 获取已选择节点 */
    getCheckedAuthorities () {
      const menuIds = []
      this.$refs['tree'].getSelectRecords().map(item => {
        menuIds.push(item.authorityId)
      })
      return menuIds.concat(this.formItem.grantActions)
    },
    handleLoadRoleApps (roleId) {
      const that = this
      this.$http.get(this.$apis.app.all, {}, this)
      .then(res => {
        this.selectApps = res.data
        this.formItem.preGrantApp = this.formItem.grantApp = res.data[0].appId
        this.handleLoadRoleGranted(roleId, this.formItem.grantApp)
      })
    },
    /* 加载权限 */
    handleLoadRoleGranted (roleId, currentApp, isBuild = true) {
      if (!roleId) {
        return
      }
      const that = this
      that.loadSuccess = false
      const p1 = that.$http.get(that.$apis.authority.appMenu, {
        appId: currentApp
      }, that)
      const p2 = that.$http.get(that.$apis.authority.roleAppAction, {
        roleId: roleId,
        appId: currentApp
      }, that)
      Promise.all([p1, p2]).then(function (values) {
        const res1 = values[0]
        const res2 = values[1]
        that.asyncData1 = res1
        that.asyncData2 = res2
        that.loadSuccess = true
        isBuild && that.buildMenuAuthority(res1, res2);
        that.modalVisible = true
      })
    },
    buildMenuAuthority(menures, authorities) {
      const that = this
      that.checkRowKeys = []
      if (menures.code === 0 && menures.data) {
        if (authorities.code === 0 && authorities.data && authorities.data.length > 0) {
          const menus = []
          const actions = []
          authorities.data.map(item => {
            // 菜单权限
            if (item.authority.indexOf('MENU_') != -1 && !menus.includes(item.authorityId)) {
              menus.push(item.authorityId)
            }
            // 操作权限
            if (item.authority.indexOf('ACTION_') != -1 && !actions.includes(item.authorityId)) {
              actions.push(item.authorityId)
            }
          })
          that.formItem.grantMenus = menus
          that.formItem.grantActions = actions
          // 时间
          if (authorities.data.length > 0) {
            that.formItem.expireTime = authorities.data[0].expireTime
            that.formItem.isExpired = authorities.data[0].isExpired
          }
        }
        menures.data.map(item => {
          // 菜单选中
          if (that.formItem.grantMenus.includes(item.authorityId)) {
            that.checkRowKeys.push(item.menuId)
          }
        })
        const opt = {
          key: 'menuId',
          parentKey: 'parentId',
          children: 'children'
        }
        that.selectMenus = XEUtils.toArrayTree(menures.data, opt)
      }
    },
    // 选择APP下拉框的事件
    selectChange (value) {
      const that = this
      if (!that.changed) {
        that.handleLoadRoleGranted(that.formItem.roleId, value)
        that.formItem.preGrantApp = value
        return
      }
      that.changed = false
      that.handleLoadRoleGranted(that.formItem.roleId, value, false)
      // 提示是否保存当前配置
      that.$Modal.confirm({
        title: '询问',
        content: '是否保存当前的权限配置?',
        onOk: () => {
          const loadMenuTimer = setInterval(function() {
            if (that.loadSuccess) {
              that.dealWithSubmit(that.formItem.preGrantApp)
              that.buildMenuAuthority(that.asyncData1, that.asyncData2)
              clearInterval(loadMenuTimer)
              that.formItem.preGrantApp = value
            }
          }, 100)
        },
        onCancel: () => {
            that.buildMenuAuthority(that.asyncData1, that.asyncData2)
            that.formItem.preGrantApp = value
        }
      })
    }
  },
  mounted: function () {
  }
}
</script>
